#define  _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"


SLTNode* CreateSListNode(SLTDatatype x)
{
	SLTNode* p = (SLTNode*)malloc(sizeof(SLTNode));
	if (!p)
	{
		perror("CreateSListNode");
		exit(-1);
	}
	p->next = NULL;
	p->data = x;
	return p;
}

void SListPrint(SLTNode* plist)
{
	assert(plist);

	SLTNode* curr = plist;
	while (curr)
	{
		printf("%d->", curr->data);
		curr = curr->next;
	}
	printf("NULL\n");
}

void SListPushBack(SLTNode** pplist, SLTDatatype x)
{
	SLTNode* p = CreateSListNode(x);
	if (*pplist == NULL)
	{
		*pplist = p;
	}
	else
	{
		SLTNode* tail = *pplist;
		while (tail->next)
		{
			tail = tail->next;
		}
		tail->next = p;
	}
}
void SListPushFront(SLTNode** pplist, SLTDatatype x)
{
	SLTNode* p = CreateSListNode(x);

	if (*pplist == NULL)
	{
		*pplist = p;
	}
	else
	{
		p->next = *pplist;
		*pplist = p;
	}
}
void SListPopBack(SLTNode** pplist)
{
	assert(*pplist);

	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SLTNode* tail = *pplist;
		SLTNode* prev = NULL;
		while (tail->next)
		{
			prev = tail;
			tail = tail->next;
		}
		prev->next = NULL;
		free(tail);
		tail = NULL;
	}
}
void SListPopFront(SLTNode** pplist)
{
	assert(*pplist);

	if ((*pplist)->next == NULL)
	{
		free(*pplist);
		*pplist = NULL;
	}
	else
	{
		SLTNode* newhead = (*pplist)->next;
		free(*pplist);
		*pplist = newhead;
	}
}
SLTNode* SListFind(SLTNode* plist, SLTDatatype x)
{
	assert(plist);

	SLTNode* curr = plist;
	while (curr)
	{
		if (curr->data = x)
			return curr;
		curr = curr->next;
	}
	return NULL;
}

void SListInsertAfter(SLTNode* pos, SLTDatatype x)
{
	assert(pos);

	SLTNode* p = CreateSListNode(x);
	p->next = pos->next;
	pos->next = p;
}
void SListEraseAfter(SLTNode* pos)
{
	assert(pos);

	SLTNode* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}

void SListDestory(SLTNode** pplist)
{
	assert(*pplist);

	SLTNode* curr = (*pplist)->next;
	while (curr)
	{
		SLTNode* del = curr;
		curr = curr->next;
		free(del);
	}
	free(*pplist);
	*pplist = NULL;
}